//
//  YGOauthViewController.swift
//  sinaWeiBoGui
//
//  Created by liyonggui on 16/5/12.
//  Copyright © 2016年 liyonggui. All rights reserved.
//

import UIKit

import SVProgressHUD

class YGOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // https://api.weibo.com/oauth2/authorize?client_id=3320703065&redirect_uri=http://www.baidu.com/
        // //api.weibo.com/oauth2/authorize?client_id=3320703065&redirect_uri=http://www.baidu.com/
        
        view.backgroundColor = GlobalBKGColor
        
        navigationItem.title = "登录"
        
        // 设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消",style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        // 加载登录界面
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        SVProgressHUD.showWithStatus("正在加载")
    }

    // MARK: - 点击事件
    @objc private func autoFill() {
        
        let jsString = "document.getElementById('userId').value='15107678913';document.getElementById('passwd').value='wokaowokao';"
        
        // 使用WebView执行JS代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
}

extension YGOauthViewController: UIWebViewDelegate {
    /// webView加载完成调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL!
        
//        YGPrint(items: "\(url.absoluteString)")
        
        //取消  http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        //授权  http://www.baidu.com/?code=b7b2fabfb61dc2ed6a8c53332836a732
        
        if !url.absoluteString.hasPrefix(redirect_uri) {
            // 不是授权回调的地址，就加载
            return true
        } else {
            // 是授权的地址,不加载, 自己处理
            let qurey = url.query!
//            YGPrint(items: "\(qurey)")
            let codeString = "code="
            if qurey.hasPrefix(codeString) {
                // 截取code值
                let code = (qurey as NSString).substringFromIndex(codeString.characters.count)
//                YGPrint(items: "\(code)")
                
                // 发送POST请求获取AccessToken, 保存到沙盒
                YGUserAccountViewModel.sharedInstance.loadAccessToken(code, callBack: { (error) -> () in
                    
                    if error != nil {
                        
                        SVProgressHUD.showErrorWithStatus("你的网络不给力...")

                        // 延迟一秒关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                        
                    } else {
                        self.close()
                        // 跳转到欢迎界面
                        let myAppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                        myAppDelegate.switchController(YGWelcomViewController())
                    }
                })
                
            } else {
                close()
            }
        }
        return false
    }
}



















